<?php 

namespace app\admin\event;

use app\common\enum\GoodsAttributeEnum;
use app\common\model\GoodsAttr as GoodsAttrModel;
use app\common\model\GoodsAttribute as GoodsAttributeModel;
use app\common\utils\JsonService;

class GoodsAttributeEvent{

    /*
    * 商品属性列表
    */
    public static function goodsAttributeList(){
        $params = array_filter(request()->param());
        $page = ! empty($params['page']) && $params['page'] >= 1 ? $params['page'] : 1;
        $where = [];
        if($attr_id = isset($params['attr_id'])){
                    $where[] = [['attr_id','=',$params['attr_id']]];
            }
            if($attr_name = isset($params['attr_name'])){
                    $where[] = [['attr_name','like',"%{$params['attr_name']}%"]];
            }
            if($type_id = isset($params['type_id'])){
                    $where[] = [['type_id','like',"%{$params['type_id']}%"]];
            }
             $condition = [
                 'with'=>['getGoodsType'],
                 'where' => $where,
                 'order' => ['attr_id' => 'desc'],
                 'paginate' => [
                     'page' => $page,
                     'query' => $params,
                ],
        ];
        $goodsAttribute = GoodsAttributeModel::getPageAll($condition)->each(function($item){
            $item['attr_input_type'] = GoodsAttributeEnum::getName('attr_input_type',$item['attr_input_type']);
            $item['attr_index'] = GoodsAttributeEnum::getBoolValue($item['attr_index']);
        });
        return $goodsAttribute;
    }


    /*
    * 新增商品属性
    */
    public static function createGoodsAttribute($data){
        try {
            GoodsAttributeModel::create($data);
        } catch (\Exception $ex) {
            return JsonService::error($ex->getMessage());
        }
        return JsonService::success();
    }

    /*
    * 更新商品属性
    */
    public static function updateGoodsAttribute($data){
        if($data['attr_input_type'] != GoodsAttributeEnum::ATTR_INPUT_TYPE_ONE){
            $data['attr_values'] = '';
        }
        try {
            GoodsAttributeModel::updateOne($data, ['attr_id' => $data['attr_id']]);
        } catch (\Exception $ex) {
            return JsonService::error($ex->getMessage());
        }
        return JsonService::success();
    }


}

